package com.icbc.DataStructuresAndAlgorithms;

public class HashTabDomo {

}

//定义哈希表
/*
 * 此哈希表的结构就是有一个数组,数组中的每个元素都对应一个链表
 */
class HashTab{
	//定义的数组,数组的每个元素都是一个链表,每个链表的每个节点就是一个员工
	private EmpLinkedList[] empLinkedListArray;
	//从外部接收的哈希表数组长度
	private int size;
	//构造函数,初始化时定义哈希表的长度
	public HashTab(int size){
		this.size = size;
		empLinkedListArray = new EmpLinkedList[size];
		//注意:在数组定义完成后,数组中的每个链表都是null,在这里需要初始化链表
		for (int i = 0; i < size; i++) {
			empLinkedListArray[i] = new EmpLinkedList();
		}
	}
	
	//添加
	public void add(EmpLinkedList.EmpNode emp){
		int sanlie = sanlie(emp.getId());
		empLinkedListArray[sanlie].add(emp);
	}
	
	//散列函数
	public int sanlie(int id){
		return id % size;
	}
	
	//遍历哈希表
	public void list(){
		for (int i = 0; i < empLinkedListArray.length; i++) {
			EmpLinkedList empLinkedList = empLinkedListArray[i];
			empLinkedList.list();
		}
	}
}

//定义链表集合
class EmpLinkedList{
	EmpNode head;
	
	public void add(EmpNode emp){
		if (head == null){
			head = emp;
		} else {
			EmpNode temp = head;
			while (temp.next != null){
				temp = temp.next;
			}
			temp.next = emp;
		}
	}
	
	public void list(){
		if (head == null){
			System.out.println("没有东西!!");
		}else{
			EmpNode temp = head;
			while (temp.next != null){
				System.out.println("id="+temp.id+",name="+temp.name+",address="+temp.address);
				temp = temp.next;
			}
		}
	}
	
	//定义链表节点
	class EmpNode{
		private int id;
		private String name;
		private String address;
		private EmpNode next;
		
		public EmpNode(int id, String name, String address) {
			this.id = id;
			this.name = name;
			this.address = address;
		}
		
		public int getId() {
			return id;
		}
		
		public void setId(int id) {
			this.id = id;
		}
		
		public String getName() {
			return name;
		}
		
		public void setName(String name) {
			this.name = name;
		}
		
		public String getAddress() {
			return address;
		}
		
		public void setAddress(String address) {
			this.address = address;
		}
		
		public EmpNode getNext() {
			return next;
		}
		
		public void setNext(EmpNode next) {
			this.next = next;
		}
	}
}



